#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_errno.h"

#include "flower_data.h"

#define GPIO_PUMP   9

#define WAIT_TIME_MS 3000
#define PUMP_ON_MS  1000
#define PUMP_OFF_MS 4000

extern float hum;
extern uint8_t type;

uint8_t pump_state_flag = 0;

//定义状态变量
typedef enum{
    STATE_HUM_COMP,         //初始态
    STATE_PUMP_ON,          //检测到S1按下
    STATE_PUMP_OFF,          //检测到S2按下
}State_of_Pump;

static void PumpOn(uint32_t ms)
{
    static uint8_t ret;

    IoTGpioSetOutputVal(GPIO_PUMP, 1);         //设置GPIO6 为高电平或低电平
    TaskMsleep(ms);
    IoTGpioSetOutputVal(GPIO_PUMP, 0);         //设置GPIO6 为高电平或低电平

}

static void *PumpTask(const char *arg)
{
    (void)arg;
    State_of_Pump state;
    static uint8_t ret;

    ret = IoTGpioInit(GPIO_PUMP);                        //初始化GPIO6 外设
    if(ret != IOT_SUCCESS){
        printf("Failed to init IO%d!\r\n",GPIO_PUMP);
    }
    else{
        printf("Succeeded init IO%d!\r\n",GPIO_PUMP);
    }
    
    ret = IoTGpioSetDir(GPIO_PUMP,IOT_GPIO_DIR_OUT);
    if(ret != IOT_SUCCESS){
        printf("Failed to set IO%d!\r\n",GPIO_PUMP);
    }
    else{
        printf("Succeeded set IO%d!\r\n",GPIO_PUMP);
    }

    while(1)
    {
        static uint8_t c;
        TaskMsleep(WAIT_TIME_MS);

        switch (state)
        {
            case STATE_HUM_COMP:{
                TaskMsleep(500);
                c = hum_func(type,hum);
                if(c == 'l'){
                    state = STATE_PUMP_ON;
                }
                else{
                    state = STATE_PUMP_OFF;
                }
                break;
            }
            case STATE_PUMP_ON:{
                pump_state_flag = 1;
                PumpOn(PUMP_ON_MS);
                pump_state_flag = 0;
                state = STATE_PUMP_OFF;
                break;
            }
            case STATE_PUMP_OFF:{
                TaskMsleep(PUMP_OFF_MS);
                state = STATE_HUM_COMP;
                break;
            }
            default:{
                state = STATE_HUM_COMP;
                break;
            }
        }

    }
}

#define PUMP_TASK_STACK_SIZE 1024 * 3
#define PUMP_TASK_PRIO 27

static void PumpEntry(void)
{
    osThreadAttr_t attr;

    attr.name = "PumpTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = PUMP_TASK_STACK_SIZE;
    attr.priority = PUMP_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)PumpTask, NULL, &attr) == NULL) {
        printf("[PumpTask] Falied to create PumpTask!\n");
    }
    else{
        printf("[PumpTask] Successed to create PumpTask! in priority:%d\n",PUMP_TASK_PRIO);
    }
}

APP_FEATURE_INIT(PumpEntry);